/**
  * 大厅房间列表 以及 断线重连都在这里
  */
module game {

    export class HallRoomListMediator extends BaseMediator {
        public static NAME: string = "HallRoomListMediator";
        public constructor(viewComponent: any = null) {
            super(HallRoomListMediator.NAME, viewComponent);
        }
        public listNotificationInterests(): Array<any> {
            return [
                PanelNotify.HALL.STAGE_RESIZE,
                PanelNotify.HALL.OPEN_ROOM_LIST,
                PanelNotify.HALL.CLOSE_ROOM_LIST,
                PanelNotify.HALL.GAME_RES_LOAD,
                PanelNotify.HALL.HALL_RECONNECTGAME,
                PanelNotify.HALL.REFRESH_USER_INFO,
                PanelNotify.HALL.BACK_HALL_BY_GAME,
                PanelNotify.HALL.JOIN_GAME_BY_HALL
            ];
        }
        private gameType: any;//当前展示什么游戏类型
        private serverAddr: Array<any>;//当前展示的游戏的所有房间集合
        private userNum: number = 0;//当前在线玩家，假人数
        private panel: HallRoomListPanel;
        public static DragonBonesLIST: Array<dragonBones.EgretArmatureDisplay> = [];

        public handleNotification(notification: puremvc.INotification): void {
            switch (notification.getName()) {
                case PanelNotify.HALL.STAGE_RESIZE:
                    if (this.panel) {
                        this.panel.width = GameConfig.curWidth()
                        this.panel.height = GameConfig.curHeight()
                    }
                    break;
                case PanelNotify.HALL.OPEN_ROOM_LIST:
                    this.gameType = notification.getBody();
                    this.panel = null;
                    this.panel = new HallRoomListPanel();
                    this.showUI(this.panel, 2, 4, true, false);
                    break;
                case PanelNotify.HALL.CLOSE_HALL:
                    this.closePanel(0);
                    break;
                case PanelNotify.HALL.GAME_RES_LOAD:
                    this.handleGameLoaded();
                    break;
                case PanelNotify.HALL.HALL_RECONNECTGAME:
                    this.handleRelinkGameRoom2(notification.getBody());
                    break;
                case PanelNotify.HALL.REFRESH_USER_INFO:
                    if (this.panel && this.panel.parent) {
                        this.panel.userIcon.source = "special_" + GameVO.getVo().wFaceID % 15;
                        this.panel.playerMoney.text = GameVO.getVo().lUserScore / 100 + "";
                    }
                    break;
                case PanelNotify.HALL.BACK_HALL_BY_GAME:
                    if (this.panel && this.panel.parent) {
                        this.exitGame();
                    }
                    break;
                case PanelNotify.HALL.JOIN_GAME_BY_HALL:
                    this.joinGame()
                    break;
            }
        }
        public initUI(): void {
            this.panel.back.addEventListener(egret.TouchEvent.TOUCH_TAP, this.closeClick, this)
            this.panel.help.addEventListener(egret.TouchEvent.TOUCH_TAP, this.helpClick, this)
            this.panel.jilu.addEventListener(egret.TouchEvent.TOUCH_TAP, this.jiluClick, this)
            this.panel.fankui.addEventListener(egret.TouchEvent.TOUCH_TAP, this.fankuiClick, this)
            this.panel.userNum_group.addEventListener(egret.TouchEvent.TOUCH_TAP, this.renshuClick, this)
            this.panel.youxishiwan.addEventListener(egret.TouchEvent.TOUCH_TAP, this.handleRelinkGameRoom, this)
            this.panel.userIcon.addEventListener(egret.TouchEvent.TOUCH_TAP, this.userIconClick, this);
            this.panel.moneyAddBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onAddMoneyBtnClick, this);
            this.panel.moneySxBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.findUserMoney, this);

        }

        public initData(): void {
            //显示假人数
            this.userNum = Math.floor(1000 + Math.random() * 1000)
            this.panel.renshu.text = this.userNum + ""
            //显示左上角玩家信息
            this.panel.userIcon.source = "special_" + GameVO.getVo().wFaceID % 15;
            this.panel.playerName.text = "ID:" + Global.cutString(GameVO.getVo().szNickName + "", 11, 1);
            this.panel.playerMoney.text = "" + GameVO.getVo().lUserScore / 100;
            //显示美女动画
            var group = new eui.Group();
            const factory = dragonBones.EgretFactory.factory;
            factory.parseDragonBonesData(RES.getRes("fangjianjuese_ske_json"));
            factory.parseTextureAtlasData(RES.getRes("fangjianjuese_tex_json"), RES.getRes("fangjianjuese_tex"));
            const armatureDisplay = factory.buildArmatureDisplay("meinv");
            armatureDisplay.animation.play();
            group.addChild(armatureDisplay)
            HallRoomListMediator.DragonBonesLIST.push(armatureDisplay)
            group.left = 250
            group.bottom = -10
            this.panel.addChildAt(group, 1);
            //显示当前界面游戏类型标题
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.DDZ) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.DDZ;
                this.panel.gameType.source = "roomType_ddz"
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.BRNN) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.BRNN;
                this.panel.gameType.source = "roomType_brnn"
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.QZNN) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.QZNN;
                this.panel.gameType.source = "roomType_qznn"
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.HLSZ) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.HLSZ;
                this.panel.gameType.source = "roomType_zjh"
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.WJL) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.WJL;
                this.panel.gameType.source = "roomType_wjl"
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.LHD) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.LHD
                this.panel.gameType.source = "roomType_lhd"
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.HHDZ) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.HHDZ
                this.panel.gameType.source = "roomType_hhdz"
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.BREBG) {
                this.serverAddr = InstructionsEnum.GAME_SERVER_DATA.BREBG
                this.panel.gameType.source = "roomType_brebg"
            }
            //房间列表数据按房间等级排序
            var len = this.serverAddr.length;
            for (var i = 0; i < len; i++) {
                var temp
                for (var j = i + 1; j < len; j++) {
                    if (this.serverAddr[i].wServerLevel < this.serverAddr[j].wServerLevel) {
                        temp = this.serverAddr[j];
                        this.serverAddr[j] = this.serverAddr[i];
                        this.serverAddr[i] = temp;
                    }
                }
            }
            this.panel.youxishiwan.visible = false
            for (let i = 0; i < this.serverAddr.length; i++) {
                var data = this.serverAddr[i];
                let roomType = new game.HallRoomTypePanel(data);
                roomType.name = data.wServerID;
                roomType.addEventListener(egret.TouchEvent.TOUCH_TAP, this.handleRelinkGameRoom, this)
                this.panel.list_group.addChild(roomType)
            }
            //列表多余3个时，需要缩小 界面才放的下
            if (this.panel.list_group.numChildren > 3) {
                for (var i = 0; i < this.panel.list_group.numChildren; i++) {
                    this.panel.list_group.getChildAt(i).scaleX = 0.6
                    this.panel.list_group.getChildAt(i).scaleY = 0.6
                }
            }

        }
        private helpClick() {
            SoundManage.startAnniuBtnLoad();
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.DDZ) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_DDZ)
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.BRNN) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_BRNN)
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.QZNN) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_QZNN)
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.HLSZ) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_HLSZ)
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.WJL) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_WJL)
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.LHD) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_LHD)
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.HHDZ) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_HHDZ)
            }
            if (this.gameType == InstructionsEnum.GAME_TYPE_NAME.BREBG) {
                game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_HELP_BREBG)
            }
        }
        private jiluClick() {
            SoundManage.startAnniuBtnLoad();
            var obj = {
                gameType: this.gameType,
                roomType: 0
            }
            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_JILU, JSON.stringify(obj))
        }
        private fankuiClick() {
            SoundManage.startAnniuBtnLoad();
            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_FANKUI)
        }
        private renshuClick(eve: egret.TouchEvent) {
            SoundManage.startAnniuBtnLoad();
            EffectUtils.playDim(eve.currentTarget)
            if (this.panel.renshuGroup.visible == true) {
                egret.Tween.removeTweens(this.panel.renshuGroup)
                this.panel.renshuGroup.visible = false
            } else {
                this.panel.renshuGroup.alpha = 1
                this.panel.renshuGroup.visible = true
                this.panel.renshuText.text = "当前在线 " + this.userNum + " 人，感谢您对越众棋牌的支持!"
                egret.Tween.get(this.panel.renshuGroup).wait(1000).to({ alpha: 0 }, 1000).to({ visible: false })
            }
        }
        private closeClick() {
            SoundManage.startAnniuBtnLoad();
            this.closePanel(3)
            //龙骨动画销毁
            for (let i = 0; i < HallRoomListMediator.DragonBonesLIST.length; i++) {
                if (HallRoomListMediator.DragonBonesLIST[i] && HallRoomListMediator.DragonBonesLIST[i].parent) {
                    HallRoomListMediator.DragonBonesLIST[i].animation.stop()
                    HallRoomListMediator.DragonBonesLIST[i].dispose();
                    HallRoomListMediator.DragonBonesLIST[i] = null;
                }
            }
            HallRoomListMediator.DragonBonesLIST.splice(0)
        }
        //打开头像设置
        private userIconClick(event: egret.TouchEvent) {
            SoundManage.startAnniuBtnLoad();
            EffectUtils.playDim(event.currentTarget)
            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_SPECIA_MODIFY)
        }
        /**
         *  进入指定的房间
         * 断线重连:根据内存中记录的游戏房间ID来加入该房间 
         * 玩家手动选中某房间，或者后台推送回到其他房间，都会将房间ID记录到InstructionsEnum.ID_GAME）
         * 务必在退出游戏后清除 InstructionsEnum.ID_GAME
         */
        private handleRelinkGameRoom2(wServerID): void {//房间ID
            InstructionsEnum.ID_GAME = wServerID
            let roomList = GameVO.getVo().roomList;
            if (Global.isNotEmpty(roomList)) {
                for (let i = 0; i < roomList.length; i++) {
                    if (roomList[i].wServerID == InstructionsEnum.ID_GAME) {
                        let wKindID = roomList[i].wKindID;
                        this.divideGameType(wKindID);
                        return;
                    }
                }
            }
        }
        //选中指定的房间(根据点击的图片确定进哪个房间)
        private handleRelinkGameRoom(event: egret.TouchEvent): void {//房间ID
            SoundManage.startAnniuBtnLoad()
            EffectUtils.playDim(event.currentTarget)
            InstructionsEnum.ID_GAME = event.currentTarget.name;
            let roomList = GameVO.getVo().roomList;
            if (Global.isNotEmpty(roomList)) {
                for (let i = 0; i < roomList.length; i++) {
                    if (roomList[i].wServerID == InstructionsEnum.ID_GAME) {
                        let wServerLevel = roomList[i].wServerLevel;
                        let wKindID = roomList[i].wKindID;
                        let lEnterScore = roomList[i].lEnterScore
                        InstructionsEnum.LEVEL_GAME = wServerLevel
                        if (GameVO.getVo().lUserScore < lEnterScore && wServerLevel != 4) {//试玩场没有入场限制
                            let obj = {
                                CODE: PanelNotify.HALL.OPEN_ADD_MONEY,
                                TEXT: "本房间入场分" + lEnterScore / 100 + "！\r是否立刻充值？",
                                NEXT: true,
                            }
                            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_TIP, obj);
                        } else {
                            this.divideGameType(wKindID)
                        }
                        return;
                    }
                }
            }
        }
        //选择房间后根据该房间所属游戏类型加载资源
        private divideGameType(wKindID: any): void {//游戏ID
            switch (wKindID) {
                case InstructionsEnum.GAME_SERVER_ID.DDZ:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.DDZ);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.QZNN:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.QZNN);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.BRNN:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.BRNN);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.HLSZ:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.HLSZ);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.WJL:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.WJL);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.LHD:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.LHD);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.HHDZ:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.HHDZ);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.BREBG:
                    resLoading.loadResGroup(InstructionsEnum.GAME_TYPE_NAME.BREBG);
                    break;
            }
        }
        //游戏资源加载完成后进入之前选择的房间
        private handleGameLoaded(): void {
            var data: any;
            let roomList = GameVO.getVo().roomList;
            if (Global.isNotEmpty(roomList)) {
                for (let i = 0; i < roomList.length; i++) {
                    if (roomList[i].wServerID == InstructionsEnum.ID_GAME) {
                        data = roomList[i];
                        break;
                    }
                }
            }
            if (Global.isEmpty(data)) {
                return;
            }
            let obj = {
                dwPlazaVersion: 101122049,
                dwFrameVersion: 101122049,
                dwProcessVersion: 101122049,
                dwUserID: GameVO.getVo().dwUserID,
                szPassword: GameVO.getVo().szDynamicPass,
                szServerPasswd: "",
                szMachineID: "",
                wGameID: data.wKindID
            }
            // InstructionsEnum.IP_LOGIN = data.szServerAddr; // IP写死在前端，后端不传IP
            InstructionsEnum.PORT_GAME = data.gamePort;
            switch (data.wKindID) {
                case InstructionsEnum.GAME_SERVER_ID.DDZ:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.DDZ, RegDataDdz.CMD_GP_LogonMobile, obj, true);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.QZNN:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.QZNN, RegDataQznn.CMD_GP_LogonMobile, obj, true);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.BRNN:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.BRNN, RegDataBrnn.CMD_GP_LogonMobile, obj, true);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.HLSZ:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.HLSZ, RegDataHlsz.CMD_GP_LogonMobile, obj, true);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.WJL:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.WJL, RegDataWjl.CMD_GP_LogonMobile, obj, true);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.LHD:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.LHD, RegDataLhd.CMD_GP_LogonMobile, obj, true);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.HHDZ:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.HHDZ, RegDataHhdz.CMD_GP_LogonMobile, obj, true);
                    break;
                case InstructionsEnum.GAME_SERVER_ID.BREBG:
                    SocketManager.sendMessage(InstructionsEnum.GAME_TYPE_NAME.BREBG, RegDataBrebg.CMD_GP_LogonMobile, obj, true);
                    break;
            }
            //把当前游戏ID写入缓存，大厅用来做 最近 标签
            var wKindID = egret.localStorage.getItem("wKindID")
            var arr: Array<any> = []
            if (wKindID != null) {
                arr = wKindID.split(",");
            }
            if (arr.indexOf(data.wKindID + "") == -1) {
                arr.push(data.wKindID + "");
            }
            arr = arr.slice(-3);
            egret.localStorage.setItem("wKindID", arr.join(","))
        }
        //从游戏中退出
        private exitGame() {
            //龙骨动画恢复运动
            for (let i = 0; i < HallRoomListMediator.DragonBonesLIST.length; i++) {
                if (HallRoomListMediator.DragonBonesLIST[i] && HallRoomListMediator.DragonBonesLIST[i].parent) {
                    HallRoomListMediator.DragonBonesLIST[i].armature.animation.play()
                }
            }
        }
        //进入游戏
        private joinGame() {
            //龙骨动画暂停
            for (let i = 0; i < HallRoomListMediator.DragonBonesLIST.length; i++) {
                if (HallRoomListMediator.DragonBonesLIST[i] && HallRoomListMediator.DragonBonesLIST[i].parent) {
                    HallRoomListMediator.DragonBonesLIST[i].animation.stop()
                }
            }
        }
        //打开充值
        private onAddMoneyBtnClick(event: egret.TouchEvent): void {
            SoundManage.startAnniuBtnLoad();
            game.AppFacade.instance.sendNotification(PanelNotify.HALL.OPEN_ADD_MONEY);
        }
        //请求用户信息（刷新金币）
        private findUserMoney() {
            //请求用户信息（刷新金币）
            var request = new egret.HttpRequest();
            request.responseType = egret.HttpResponseType.TEXT;
            request.open(InstructionsEnum.IP_API + "/gameinfo/GetScoreInfo?uid=" + GameVO.getVo().dwUserID + "&isGuest=" + InstructionsEnum.isGuest, egret.HttpMethod.GET);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.addEventListener(egret.Event.COMPLETE, (event: egret.Event) => {
                EffectUtils.hideWaritPanel()
                var request = <egret.HttpRequest>event.currentTarget;
                var obj = JSON.parse(request.response)
                var Score = obj["Score"]
                if (Score) {
                    GameVO.getVo().lUserScore = Number(Score);
                    game.AppFacade.instance.sendNotification(PanelNotify.HALL.REFRESH_USER_INFO)
                }
            }, this);
            request.addEventListener(egret.IOErrorEvent.IO_ERROR, () => {
                EffectUtils.hideWaritPanel()
                Global.tipShow("网络请求失败，请稍后重试!")
            }, this);
            request.send();
            EffectUtils.showWaritPanel()
        }
    }
}